package com.example.treasure_back.controller;

import com.example.treasure_back.entity.BusinessException;
import com.example.treasure_back.entity.MsgEntity;
import com.example.treasure_back.model.vo.CoinViewModel;
import com.example.treasure_back.service.CoinService;
import com.example.treasure_back.shiroEntity.auth.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/treasure/coin")
public class CoinController {

    @Autowired
    private CoinService coinService;


    @RequestMapping("/getCoinByEmail")
    public MsgEntity getCoinByEmail(@AuthUser String email){
        Integer coin = coinService.getCoinByEmail(email);
        return new MsgEntity("SUCCESS", "200", coin);
    }

    @RequestMapping("/reduceCoinByEmail/{id}")
    public MsgEntity reduceCoinByEmail(@AuthUser String email, @PathVariable Integer id){
        String code = coinService.reduceCoinByEmail(email, id);
        if (code.equals("200")) {
            return new MsgEntity("SUCCESS", code, "兑换成功");
        }
        else if(code.equals("-1")){
            throw new BusinessException(code, "余额不足，兑换失败");
        }
        else{
            throw new BusinessException(code, "该商品已售击，请选择其他商品");
        }
    }

    @RequestMapping("/getCoinView")
    public MsgEntity getCoinView(@AuthUser String email){
        List<CoinViewModel> coinView = coinService.getCoinView(email);
        return new MsgEntity("SUCCESS","200", coinView);
    }

    @RequestMapping("/deleteCoinChangeRecord/{id}")
    public MsgEntity deleteCoinChangeRecord(@PathVariable Integer id,@AuthUser String email){
        Boolean b = coinService.deleteCoinChangeRecord(email, id);
        if (!b){
            throw new BusinessException("-1", "为找到相关记录");
        }
        return new MsgEntity("SUCCESS","200","操作成功");
    }
}
